package com.eightbears.beboy.ui.user.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.PayOrderAdapter;
import com.eightbears.beboy.base.BaseFragment;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.PayOrderEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.user.activity.OrderDetailActivity;
import com.eightbears.beboy.ui.user.activity.PaymentActivity;
import com.eightbears.beboy.ui.user.activity.PostDetailActivity;
import com.eightbears.beboy.ui.user.activity.ShowSetMealInfoActivity;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER_ACCEPT;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER_ACCEPT_VALUE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_ORDER_WAIT_PAY;
import static com.eightbears.beboy.base.util.CommonAPI.URL_PAY_ORDER;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.entity.WaitPaymentEntity.PARAMS_WAIT_PAYMENT;
import static com.eightbears.beboy.ui.user.activity.BuyResultActivity.EVENT_BUY_SET_MEAL_SUCCESS;
import static com.eightbears.beboy.ui.user.activity.OrderDetailActivity.PARAMS_PAY_ORDER;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.PARAMS_POST_ID;

public class SetMealOrderFragment extends BaseFragment implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.view_empty)
    View view_empty;

    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;

    private PayOrderAdapter payOrderAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_all_order, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
        return view;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        initAdapter();
        getData();
    }

    @Override
    protected void initEvent() {
        payOrderAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                PayOrderEntity.PayOrder payOrder = (PayOrderEntity.PayOrder) adapter.getData().get(position);

                switch (view.getId()) {
                    case R.id.rl_post_item:
                    case R.id.tv_read:
                        startLocalActivity(PostDetailActivity.class, PARAMS_POST_ID, payOrder.getObject_id());
                        break;
                    case R.id.tv_shopbook_mealbug:
                        if(payOrder.getStatus().equals(STATUS_ORDER_WAIT_PAY)) {
                            if (view.getTag().equals(STATUS_ORDER_WAIT_PAY)) {
                                startLocalActivity( PaymentActivity.class, PARAMS_WAIT_PAYMENT, payOrder);
                            }
                        } else {
                            startLocalActivity(ShowSetMealInfoActivity.class, PARAMS_PAY_ORDER, payOrder);
                        }
                        break;
                    case R.id.shop_info_meal:
                        startLocalActivity(OrderDetailActivity.class, PARAMS_PAY_ORDER, payOrder);
                        break;
                }
            }
        });
    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        payOrderAdapter = new PayOrderAdapter();
        rv_list.setLayoutManager(new MyLinearLayoutManager(getActivity()));
        payOrderAdapter.openLoadAnimation();
        payOrderAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(payOrderAdapter);
    }

    private void getData() {
        swipeLayout.setRefreshing(true);
        OkHttpUtils.get().url(URL_PAY_ORDER)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addHeader(KEY_HTTP_HEADER_ACCEPT, KEY_HTTP_HEADER_ACCEPT_VALUE)
                .addParams("page", String.valueOf(page))
                .addParams("size", String.valueOf(PARAMS_PAGE_SIZE))
                .addParams("status", "[0, 1, 2, 3, 6]")
                .addParams("type", "[4]")
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                PayOrderEntity payOrderEntity = GsonUtil.fromJson(response, PayOrderEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(payOrderEntity.getStatus_code())) {
                    isEnd = payOrderEntity.getData().getIs_end();
                    if (page == 1) {
                        payOrderAdapter.setNewData(payOrderEntity.getData().getList());
                        if (payOrderEntity.getData().getList().size() == 0)
                            view_empty.setVisibility(View.VISIBLE);
                        else
                            view_empty.setVisibility(View.GONE);
                    } else {
                        payOrderAdapter.addData(payOrderEntity.getData().getList());
                        payOrderAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    @Override
    public void onRefresh() {
        payOrderAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                payOrderAdapter.getData().clear();
                getData();
                payOrderAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    payOrderAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(getActivity(), R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        payOrderAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_BUY_SET_MEAL_SUCCESS:
                onRefresh();
                break;
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
